﻿using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WinformFramework.Utility;

namespace BackupTool
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();

            if (File.Exists(Environment.CurrentDirectory + @"\Backup.ini"))
            {
                LoadServerSetting();
            }
        }
        
        string ConnectionString
        {
            get { return String.Format("server={0};database=master;uid={1};pwd={2}", 
                Server, UserName, Password); }
        }
        public string Server { get { return ServerTxd.Text; } }
        public string UserName { get { return UserNameTxd.Text; } }
        public string Password { get { return PasswordTxd.Text; } }
        private void LoadAllDatabase()
        {
            SQLHelper sqlHelper = new SQLHelper(ConnectionString);
            string sql = @"SELECT name FROM master..SysDatabases WHERE dbid NOT IN (1,2,3,4) ORDER BY name";
            DataTable table = sqlHelper.ExecuteDataTable(sql);
            ForBackupSelector.Items.Clear();
            foreach (DataRow row in table.Rows)
                ForBackupSelector.Items.Add(row["name"]);
        }
        public void AutoBackup()
        {
            LoadServerSetting();
            LoadAllDatabase();
            LoadBackupSetting();
            Backup();
        }
        public void LoadServerSetting()
        {
            IniHelper iniHelper = new IniHelper(Environment.CurrentDirectory + @"\Backup.ini");
            ServerTxd.Text = iniHelper.ReadValue("Connection", "Server");
            UserNameTxd.Text = iniHelper.ReadValue("Connection", "UserName");
            PasswordTxd.Text = iniHelper.ReadValue("Connection", "Password");
        }

        public void LoadBackupSetting()
        {
            IniHelper iniHelper = new IniHelper(Environment.CurrentDirectory + @"\Backup.ini");
            var isCompress = iniHelper.ReadValue("Backup", "IsCompress");
            ForBackupIsCompressCb.Checked = String.IsNullOrWhiteSpace(isCompress) ? false : Boolean.Parse(isCompress);
            ForBackupSavePathTxd.Text = iniHelper.ReadValue("Backup", "BackupPath");

            var isSend = iniHelper.ReadValue("Backup", "IsSend");
            ForBackupIsSendCb.Checked = String.IsNullOrWhiteSpace(isSend) ? false : Boolean.Parse(isSend);
            ForBackupSendPathTxd.Text = iniHelper.ReadValue("Backup", "SendPath");

            LoadAllDatabase();

            string selectedDatabasesString = iniHelper.ReadValue("Backup", "SelectedDatabases");
            if (!String.IsNullOrWhiteSpace(selectedDatabasesString))
            {
                string[] selectedDatabases = selectedDatabasesString.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < ForBackupSelector.Items.Count; i++)
                {
                    if (selectedDatabases.Contains(ForBackupSelector.Items[i]))
                    {
                        ForBackupSelector.SetItemChecked(i, true);
                    }
                }
            }
        }
        public void Backup()
        {
            var folderName = DateTime.Now.ToString("yyyyMMddHHmmss");
            var bakFolderName = String.Format(@"{0}\{1}", ForBackupSavePathTxd.Text, folderName);
            Directory.CreateDirectory(bakFolderName);
            for (int i = 0; i < ForBackupSelector.Items.Count; i++)
            {
                if (ForBackupSelector.GetItemChecked(i))
                {
                    SQLHelper sqlHelper = new SQLHelper(ConnectionString);
                    string dbName = (string)ForBackupSelector.Items[i];
                    string sql = String.Format(@"BACKUP DATABASE {0} TO DISK = '{1}\{0}.bak' ", dbName, bakFolderName);
                    sqlHelper.ExecuteNonQuery(sql);
                }
            }
            if (ForBackupIsCompressCb.Checked)
            {
                (new FastZip()).CreateZip(String.Format(@"{0}\{1}.zip", ForBackupSavePathTxd.Text, folderName), String.Format(@"{0}\{1}", ForBackupSavePathTxd.Text, folderName), true, "");
                Directory.Delete(bakFolderName, true);
            }
            if (ForBackupIsSendCb.Checked)
            {
                File.Copy(String.Format(@"{0}\{1}.zip", ForBackupSavePathTxd.Text, folderName),
                    String.Format(@"{0}\{1}.zip", ForBackupSendPathTxd.Text, folderName));
            }
        }
        private void LinkBtn_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrWhiteSpace(Server) || String.IsNullOrWhiteSpace(UserName) 
                || String.IsNullOrWhiteSpace(Password))
                return;
            try
            {
                LoadAllDatabase();
                LoadBackupSetting();
                tabControl1.Enabled = true;
            }
            catch (Exception ex)
            {
                tabControl1.Enabled = false;
                MessageBox.Show(ex.Message);
            }
        }
        private void SelectAllDatabaseBtn_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < ForBackupSelector.Items.Count; i++)
            {
                ForBackupSelector.SetItemChecked(i, true);
            }
        }

        private void DeselectAllDatabaseBtn_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < ForBackupSelector.Items.Count; i++)
            {
                ForBackupSelector.SetItemChecked(i, false);
            }
        }

        private void SaveBackupSettingBtn_Click(object sender, EventArgs e)
        {
            IniHelper iniHelper = new IniHelper(Environment.CurrentDirectory + @"\Backup.ini");
            iniHelper.WriteValue("Connection", "Server", Server);
            iniHelper.WriteValue("Connection", "UserName", UserName);
            iniHelper.WriteValue("Connection", "Password", Password);
            List<string> selectedDatabases = new List<string>();
            for (int i = 0; i < ForBackupSelector.Items.Count; i++)
            	if (ForBackupSelector.GetItemChecked(i))
                    selectedDatabases.Add((string)ForBackupSelector.Items[i]);
                

            iniHelper.WriteValue("Backup", "SelectedDatabases", String.Join(",", selectedDatabases.ToArray()));
            iniHelper.WriteValue("Backup", "BackupPath", ForBackupSavePathTxd.Text);
            iniHelper.WriteValue("Backup", "SendPath", ForBackupSendPathTxd.Text);
            iniHelper.WriteValue("Backup", "IsCompress", ForBackupIsCompressCb.Checked.ToString());
            iniHelper.WriteValue("Backup", "IsSend", ForBackupIsSendCb.Checked.ToString());
        }

        private void ForBackupSavePathBtn_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ForBackupSavePathTxd.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void ForBackupStart_Click(object sender, EventArgs e)
        {
            Backup();
        }

        private void SelectAllBackupBtn_Click(object sender, EventArgs e)
        {

        }

        private void DeselectAllBackupBtn_Click(object sender, EventArgs e)
        {

        }

        private void ForRestoreFilePathBtn_Click(object sender, EventArgs e)
        {

        }

        private void ForRestoreSavePathBtn_Click(object sender, EventArgs e)
        {

        }

        private void ForRestoreStart_Click(object sender, EventArgs e)
        {

        }

        private void ForBackupSendPathBtn_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ForBackupSendPathTxd.Text = folderBrowserDialog1.SelectedPath;
            }
        }
    }
}
